package top.lingkang.mm.solon;

import org.noear.solon.core.aspect.Interceptor;
import org.noear.solon.core.aspect.Invocation;
import top.lingkang.mm.transaction.TransactionManage;

/**
 * 事务拦截处理
 *
 * @author lingkang
 * @create by 2024/3/4 15:50
 */
public class TransactionalInterceptor implements Interceptor {
    private static final ThreadLocal<Integer> number = ThreadLocal.withInitial(() -> 0);

    @Override
    public Object doIntercept(Invocation inv) throws Throwable {
        Integer current = number.get();
        if (current == 0) {
            TransactionManage.beginTransaction();
        }
        current++;
        number.set(current);

        try {
            Object result = inv.invoke();
            current--;
            if (current == 0) {
                TransactionManage.commit();
            } else {
                number.set(current);
            }
            return result;
        } catch (Exception e) {
            number.set(0);
            TransactionManage.rollback();
            throw e;
        }
    }
}
